﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Windows.Resources;
using System.IO;

namespace SkyPoint
{
    public class CSVLoader
    {
        Dictionary<string, Color> colors;



        public List<SkyObject> ExtractStars()
        {
            colors = new Dictionary<string, Color>();
            mapColors();
            List<SkyObject> skyObjects = new List<SkyObject>();
            StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("test.csv", UriKind.Relative));
            StreamReader sr = new StreamReader(streamInfo.Stream);
            string line = sr.ReadLine(); //Dispose of headers
            line = sr.ReadLine();
            while (line != null)
            {
                SkyObject skyObject = parseSkyObject(line);
                if(!String.IsNullOrWhiteSpace(skyObject.Designation)) skyObjects.Add(parseSkyObject(line));
                line = sr.ReadLine();
            }

            return skyObjects;
        }

        private void mapColors()
        {
            colors.Add("O", Color.FromArgb(255, 154, 175, 255));
            colors.Add("B", Color.FromArgb(255, 170, 191, 255));
            colors.Add("A", Color.FromArgb(255, 202, 215, 255));
            colors.Add("F", Color.FromArgb(255, 248, 247, 255));
            colors.Add("G", Color.FromArgb(255, 255, 244, 234));
            colors.Add("K", Color.FromArgb(255, 255, 193, 51));
            colors.Add("M", Color.FromArgb(255, 255, 125, 51)); 
        }


        private SkyObject parseSkyObject(string row)
        {
            string[] tokens = row.Split(',');
            string name;
            string designation;
            if (String.IsNullOrWhiteSpace(tokens[1]))
            {
                name = tokens[0];
                designation = "";
            }
            else
            {
                name = tokens[1];
                designation = tokens[0];
            }
            Color c;
            colors.TryGetValue(tokens[5].Substring(0,1),out c);
            if(c == null) c = Color.FromArgb(255, 248, 247, 255);
            return new SkyObject(new Coord(Double.Parse(tokens[2]), Double.Parse(tokens[3])), //right ascension, declination
                                 name, //name
                                 designation,
                                 Double.Parse(tokens[4]), //magnitude
                                 c); //color
        }
    }
}
